Editable List

1import { Color, EditButton, ForEach, List, Navigation, NavigationStack, Script, Text, useState } from "scripting"
2
3function Example() {
4  const [colors, setColors] = useState<Color[]>([
5    "red",
6    "orange",
7    "yellow",
8    "green",
9    "blue",
10    "purple",
11  ])
12
13  function onDelete(indices: number[]) {
14    setColors(colors.filter((_, index) => !indices.includes(index)))
15  }
16
17  function onMove(indices: number[], newOffset: number) {
18    const movingItems = indices.map(index => colors[index])
19    const newColors = colors.filter((_, index) => !indices.includes(index))
20    newColors.splice(newOffset, 0, ...movingItems)
21    setColors(newColors)
22  }
23
24  return <NavigationStack>
25    <List
26      navigationTitle={"Editable List"}
27      navigationBarTitleDisplayMode={"inline"}
28      toolbar={{
29        confirmationAction: [
30          <EditButton />,
31        ]
32      }}
33    >
34      <ForEach
35        count={colors.length}
36        itemBuilder={index =>
37          <Text
38            key={colors[index]} // Must provide a unique key!!!
39          >{colors[index]}</Text>
40        }
41        onDelete={onDelete}
42        onMove={onMove}
43      />
44    </List>
45  </NavigationStack>
46}
47
48async function run() {
49  await Navigation.present({
50    element: <Example />
51  })
52
53  Script.exit()
54}
55
56run()